import { useAtomValue } from "jotai";
import { AnimatePresence, m } from "framer-motion";
import { useCallback, useEffect, useState } from "react";
import { useLatestRef, useSearchParam } from "shared/hooks";
import { Popover, Tooltip } from "shared/components";
import { debounce, download } from "shared/helpers";
import { sortedEventsAtom } from "@/store/events";
import BackTopIcon from "@/assets/icons/back-top.svg?jsx";
import DownloadIcon from "@/assets/icons/download.svg?jsx";
import { defaultPerson } from "@/lib/constants";

const orderMap = [
  ["type", "事件类型"],
  ["time", "事件时间"],
  ["title", "事件标题"],
  ["content", "事件内容"],
  ["people", "相关人物"],
  ["place", "相关地点"],
  ["organization", "相关机构"],
];

export default function FixedButtons() {
  return (
    <AnimatePresence>
      <Download key="download" />
      <BackTop key="backtop" />
    </AnimatePresence>
  );
}

function BackTop() {
  const [show, setShow] = useState(false);

  useEffect(() => {
    const handleScroll = debounce(function (this: Window, e: Event) {
      setShow(this.scrollY >= 200);
    }, 100);
    // init
    setShow(window.scrollY >= 200);
    window.addEventListener("scroll", handleScroll);
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  if (!show) {
    return null;
  }

  return (
    <Tooltip
      content="返回顶部"
      placement="left"
      className="fixed bottom-8 right-4 size-9"
      placementOffset={10}
    >
      <m.button
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        className="text-[#0B9682]/40 transition-colors hover:text-[#077741]"
        onClick={() => window.scroll({ top: 0, behavior: "smooth" })}
      >
        <BackTopIcon />
      </m.button>
    </Tooltip>
  );
}

function Download() {
  const [popoverVisible, setPopoverVisible] = useState(false);
  const events = useAtomValue(sortedEventsAtom);
  const eventsRef = useLatestRef(events);
  const name = useSearchParam("name", defaultPerson);

  const handleDownloadAsMarkdown = useCallback(() => {
    setPopoverVisible(false);
    let mdstr = "|" + orderMap.map((field) => field[1]).join("|") + "|\n";
    mdstr += "|" + orderMap.map(() => "-").join("|") + "|\n";
    eventsRef.current.forEach((event) => {
      mdstr +=
        "|" +
        orderMap
          .map((field) => {
            const t = event[field[0]];
            return typeof t === "string"
              ? t
              : Array.isArray(t)
                ? t.join(",")
                : "";
          })
          .join("|") +
        "|\n";
    });
    console.log(mdstr);
    download(mdstr, `${name}人物年谱.md`);
  }, []);

  const handleDownloadAsCSV = useCallback(() => {
    setPopoverVisible(false);
    let csvstr = orderMap.map((field) => field[1]).join(",") + "\n";
    eventsRef.current.forEach((event) => {
      csvstr +=
        orderMap
          .map((field) => {
            const t = event[field[0]];
            return typeof t === "string"
              ? '"' + t + '"'
              : Array.isArray(t)
                ? `"${t.join(",")}"`
                : "";
          })
          .join(",") + "\n";
    });
    console.log(csvstr);
    download(csvstr, `${name}人物年谱.csv`);
  }, []);

  if (events.length === 0) {
    return null;
  }

  return (
    <Popover
      open={popoverVisible}
      onOpenChange={setPopoverVisible}
      trigger={
        <Tooltip
          content="下载"
          placement="left"
          placementOffset={10}
          className="fixed bottom-20 right-4"
        >
          <m.button
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="size-9 text-[#0B9682]/40 transition-colors hover:text-[#077741]"
          >
            <DownloadIcon />
          </m.button>
        </Tooltip>
      }
      title="内容下载"
      placement="top"
      align="end"
      showClose
      contentClassName="bg-[#077741] text-white w-96"
    >
      <p className="text-sm">
        将当前页面内容以 Markdown 或 CSV 格式下载保存到本地。
      </p>
      <div className="mt-4 flex justify-end gap-4 text-xs">
        <button
          onClick={handleDownloadAsMarkdown}
          className="rounded bg-white px-2 py-1 text-[#077741]"
        >
          下载为Markdown
        </button>
        <button
          onClick={handleDownloadAsCSV}
          className="rounded bg-white px-2 py-1 text-[#077741]"
        >
          下载为CSV
        </button>
      </div>
    </Popover>
  );
}
